﻿CREATE PROCEDURE Sync.SP_Receipts_SelectChanges
@LastRowVersion rowversion,
@FilterdColumn UNIQUEIDENTIFIER
AS 
BEGIN 
	SELECT 
        t.[ReceiptID],
		g.[ReceiptNumber],g.[ReceiptDate],g.[ReceiptTypeID],g.[ReceiptAmount],
		t.IsDeleted,
		t.LastUpdatedDate
	FROM [dbo].[Receipts] g RIGHT JOIN Sync.Receipts_Tracking t  
    ON t.ReceiptID = g.ReceiptID 
	WHERE (@LastRowVersion IS NULL OR t.Version > @LastRowVersion)
	AND ((@FilterdColumn IS NULL) OR (
		(g.ReceiptID in (	SELECT     Receipts.ReceiptID
							FROM         CustomerLoans INNER JOIN
							Receipts ON CustomerLoans.ReceiptID = Receipts.ReceiptID
							WHERE     (CustomerLoans.CommitteeID = @FilterdColumn))
		or g.ReceiptID in (	SELECT     Receipts.ReceiptID
							FROM         Receipts INNER JOIN
							LoanInstallmentPayments ON Receipts.ReceiptID = LoanInstallmentPayments.ReceiptID INNER JOIN
							LoanExecutionInstallments ON LoanInstallmentPayments.LoanExecutionInstallmentID = LoanExecutionInstallments.LoanExecutionInstallmentID INNER JOIN
							LoanExecution ON LoanExecutionInstallments.LoanExecutionID = LoanExecution.LoanExecutionID INNER JOIN
							CustomerLoans ON LoanExecution.LoanID = CustomerLoans.LoanID
							WHERE     (CustomerLoans.CommitteeID = @FilterdColumn))
		or g.ReceiptID in (	SELECT     CommitteeBankAccountDepositReceipts.ReceiptID
							FROM         CommitteeBankAccountDepositReceipts INNER JOIN
							CommitteeBankAccountDeposites ON 
							CommitteeBankAccountDepositReceipts.CommitteeBankAccountDepositID = CommitteeBankAccountDeposites.CommitteeBankAccountDepositID INNER JOIN
							CommitteeBankAccount ON CommitteeBankAccountDeposites.CommitteeBankAccountID = CommitteeBankAccount.CommitteeBankAccountID
							WHERE     (CommitteeBankAccount.CommitteeID = @FilterdColumn)))))
    END














